package cate.game.pvp.teampvp;

import cate.game.framework.ModuleMan;
import cate.game.framework.ThreadShare;
import cate.game.pvp.teampvp.dto.TeamPvpReportData;
import cate.game.role.Role;
import cate.game.role.pvp.teampvp.msg.TeamPvpDataResp;
import cate.game.role.pvp.teampvp.msg.TeamPvpRedPointResp;
import cate.game.role.pvp.teampvp.msg.TeamPvpReplayNoticeResp;
import org.apache.commons.lang3.StringUtils;

public class TeamPvpRecvManager extends ModuleMan {
    @Override
    public void initDependent() throws Exception {
        game.rpcRecv().onFireAndForgetTemplate(TeamPvpMsg.REPORT_NOTICE,
                TeamPvpReportData.class,
                (head, msg) -> handleReport(msg));
        game.rpcRecv().onFireAndForgetTemplate(TeamPvpMsg.TEAM_NOTICE,
                String.class,
                (head, msg) -> handleTeam(msg));
        game.rpcRecv().onFireAndForgetTemplate(TeamPvpMsg.RED_POINT,
                String.class,
                (head, msg) -> handleRedPoint(msg));
    }

    private void handleReport(TeamPvpReportData report) {
        if (report == null || report.report == null || StringUtils.isBlank(report.uid)) {
            return;
        }
        Role role = game.role.getRole(report.uid);
        if (role != null) {
            log.info("收到group服组队竞技战报, role={}, uid={}, 挑战者是{}, ", role.getBase().name, role.getUid(), report.report.challengerUid);
            role.getPvp().teamPvp.addReports(report.report);
            if (role.getStatus().isOnline()) {
                ThreadShare.instance().exe(role, () -> {
                    if (StringUtils.equals(report.report.challengerUid, role.getUid())) {
                        role.sendNow(new TeamPvpReplayNoticeResp(report.report));
                    }
                    role.sendNow(new TeamPvpDataResp(role));
                });
            }
        }
    }

    private void handleTeam(String roleUid) {
        if (StringUtils.isBlank(roleUid)) {
            return;
        }
        Role role = game.role.getRole(roleUid);
        if (role != null && role.getStatus().isOnline()) {
            ThreadShare.instance().exe(role, () ->
                role.sendNow(new TeamPvpDataResp(role)));
        }
    }

    private void handleRedPoint(String roleUid) {
        if (StringUtils.isBlank(roleUid)) {
            return;
        }
        Role role = game.role.getRole(roleUid);
        if (role != null && role.getStatus().isOnline()) {
            ThreadShare.instance().exe(role, () ->
                    role.sendNow(new TeamPvpRedPointResp()));
        }
    }
}
